<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '仓储' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  data_ini:{
    type: [],
    category_id:[]
  },
  drug_all:[]
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '品项',
  initForm: {},
  doCreate: api.createProject,
  doUpdate: api.updateProject,
  doDelete: api.deleteProject,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
  api.getProjectIni().then((res) => (data.data_ini = res.data))
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '分类',
    key: 'type',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.type_name })
    },
  },
    {
    title: '图片/项目名称',
    key: 'image',
    width: 80,
    align: 'left',

    render(row) {

      return h(NFlex, {},
        [h(NAvatar, {
          src: row.image,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.title)
        })]
      )

    },
  },
  {
    title: '单价',
    key: 'price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '上架状态',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        checkedValue: 1,
        uncheckedValue: 0,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
    {
    title: '单独出售',
    key: 'is_sell',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.is_sell_name })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.status = row.status === 1 ? 0 : 1
  try {
    await api.updateProject(row)
    $message?.success(row.status ? '已上架' : '已下架')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.status = row.status === 1 ? 0 : 1
  }
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}

const customRequestMethod = (options) => {
    console.log(options, 'options');
    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code === 200) {
                modalForm.value.image = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}


const onCreate = () => {
  return {
    drug_id: '',
    range:''
  }
}
function on_add(){
  handleAdd()
  modalForm.value.is_sell = 1
  modalForm.value.status = 1
  modalForm.value.extra = 1
  get_drug_all()
}

function on_edit(row){
  handleEdit(row)
  get_drug_all()
}

function get_drug_all(){
  if(data.drug_all.length===0){
    api.getProjectDrug().then((res) => (data.drug_all = res.data))
  }
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton  type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建{{ nameFromInstance }}
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getProjectList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem :label="nameFromInstance+'名称'" :label-width="80">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 800px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <n-tabs type="line" animated size="large" pane-style="padding: 20px 0 0 0;">
               <n-tab-pane name="基础信息">
                <NFormItem label="类型" path="type">
                  <NSelect
                    v-model:value="modalForm.type"
                    :options="data.data_ini.type"
                    placeholder="请选择类型"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="项目分类" path="category_id">
                  <n-tree-select
                    v-model:value="modalForm.category_id"
                    :options="data.data_ini.category_id"
                    placeholder="请选择类型"
                    label-field="name"
                    key-field="id"
                    children-field="child"
                  />
                </NFormItem>
                <NFormItem label="名称" path="title">
                  <NInput v-model:value="modalForm.title" clearable placeholder="请输入名称" />
                </NFormItem>
                <NFormItem label="价格" path="price">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.price" placeholder="请输入价格" />
                </NFormItem>
                <NFormItem label="单独出售" path="is_sell">
                  <NSwitch
                    v-model:value="modalForm.is_sell"
                    :checked-value="1"
                    :unchecked-value="0"
                  />
                </NFormItem>
                <NFormItem label="上架状态" path="status">
                  <NSwitch
                    v-model:value="modalForm.status"
                    :checked-value="1"
                    :unchecked-value="0"
                  />
                </NFormItem>
                <NFormItem label="封面图" path="image" style="width:100%">
                    <NImage v-if="modalForm.image" width="60" style="border-radius: 5px;margin-right: 15px;"
                        :src="modalForm.image"></NImage>
                    <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" :max="1"
                        :show-file-list=false :custom-request="customRequestMethod" list-type="image">
                        <NButton>上传</NButton>
                    </NUpload>
                </NFormItem>
              </n-tab-pane>
              <n-tab-pane name="耗材信息">
                <NFormItem label="额外耗材" path="extra">
                  <NSwitch
                    v-model:value="modalForm.extra"
                    :checked-value="1"
                    :unchecked-value="0"
                  />
                </NFormItem>
                <NFormItem label="耗材模板" path="project_material_temp">
                  <n-layout>
                        <n-layout-header>
                          <n-flex >
                            <n-tag size="large" style="width: 250px"> 药品 </n-tag>
                            <n-tag size="large" style="width: 100px"> 范围 </n-tag>
                          </n-flex>
                        </n-layout-header>
                        <n-layout-content content-style="padding: 10px 0;" style="width: 593px">
                          <n-dynamic-input v-model:value="modalForm.project_material_temp" :on-create="onCreate">
                            <template #default="{ value , index}">
                              <n-flex justify="space-between">
                                <NSelect
                                  v-model:value="value.drug_id"
                                  :options="data.drug_all"
                                  placeholder="请选择药品"
                                  filterable
                                  label-field="name"
                                  value-field="id"
                                  style="width: 250px"
                                />
                                <n-input placeholder="请输入范围" v-model:value="value.range" style="width: 100px"/>
                              </n-flex>
                            </template>
                          </n-dynamic-input>
                        </n-layout-content>
                      </n-layout>
                </NFormItem>
               </n-tab-pane>
            </n-tabs>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
